package cn.com.kh;

import cn.com.elite.Util;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class FDDUtils {
    private static final Log log = LogFactory.getLog(FDDUtils.class);

    // 解析Mapn值(此方法增加需要解析的key不存在保护)
    public static String GetMapV(Map inMap, String getKey) {
        String Rev_Value = null;
        try {
            if (inMap.containsKey(getKey)) {
                Rev_Value = String.valueOf(inMap.get(getKey));
            }
        } catch (Exception e) {

            Rev_Value = "";
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }

    // 解析Json值(此方法增加需要解析的key不存在保护)
    public static String GetSFJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getLong(getKey));
            } catch (Exception e11) {
                try {
                    Rev_Value = String.valueOf(inJson.getInt(getKey));
                } catch (Exception e1) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                    } catch (Exception e2) {
                        try {
                            Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                        } catch (Exception e3) {
                            Rev_Value = "";
                        }
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }

    // 加密bizContent
    public static String encodeBizContent(String bizContentStr) throws Exception {
        // log.debug("加密bizContent前:" + bizContentStr);
        String encodedObject = URLEncoder.encode(bizContentStr, "UTF-8");
        String bizContent = new BASE64Encoder().encodeBuffer(encodedObject.getBytes(StandardCharsets.UTF_8));

        // 替换掉特殊字符
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", "");

        // log.debug("加密bizContent后:" + bizContent);
        return bizContent;
    }

    // 解密bizContent
    public static String decodeBizContent(String bizContent) throws Exception {
        // log.debug("解密bizContent前:" + bizContent);
        byte[] bytes = new BASE64Decoder().decodeBuffer(bizContent);
        String bizContentStr = URLDecoder.decode(new String(bytes), "UTF-8");
        // log.debug("生解密bizContent后:" + bizContentStr);
        return bizContentStr;
    }

    // 回调解析到Json
    public static JSONObject callbackParse(String callJsonStr) throws Exception {
        // log.info("回调解析到Json 调用请求信息:" + callJsonStr);
        JSONObject callJson = JSONObject.fromObject(callJsonStr);
        String bizContent = decodeBizContent(GetSFJV(callJson, "bizContent"));
        JSONObject bizContentJson = JSONObject.fromObject(bizContent);
        callJson.put("bizContent", bizContentJson);
        // log.info("回调解析到Json 解析结果:" + callJson);
        return callJson;
    }

    // 封装请求Json
    public static JSONObject getCallBody(String APPID, String APPKEY, String callJsonStr) throws Exception {
        log.info("⏳封装请求Json 调用请求信息:" + callJsonStr);
        JSONObject callJson = new JSONObject();

        String bizContent = FDDUtils.encodeBizContent(callJsonStr);
        bizContent = bizContent.replaceAll("\\n", "").replaceAll("\\r", "");

        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        callJson.put("timestamp", datetime);
        callJson.put("bizContent", bizContent);
        callJson.put("signType", "SHA256");
        callJson.put("appId", APPID);
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        // log.debug("✝请求报文签名前callJson：" + callJson);

        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        // log.debug("请求报文签名signstr1：" + signstr1);

        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        //log.debug("请求报文签名signstr2：" + signstr2);

        String sign = new BASE64Encoder().encode(signstr2.getBytes(StandardCharsets.UTF_8));
        // log.debug("请求报文签名sign：" + sign);
        callJson.put("sign", sign.replaceAll("\\n", "").replaceAll("\\r", ""));
        // log.debug("⬆封装请求Json 请求Body:" + callJson);

        return callJson;
    }

}
